/*
 * Copyright (c) 2009, Katholieke Universiteit Leuven
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of the Katholieke Universiteit Leuven nor the names of
 *       its contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * @addtogroup nf
 * @{
 */
/**
 * @file
 * Implementation of the LooCI Networking Framework
 * @author
 * Wouter Horré <wouter.horre@cs.kuleuven.be>
 */

#include "contiki-net.h"
#include "networking_private.h"
#include "events_private.h"
#include "peers.h"
#include "memb.h"
#include <string.h>

#ifdef LOOCI_NF_DEBUG
#include <stdio.h>
#ifdef CONTIKI_TARGET_AVR_RAVEN
#include <avr/pgmspace.h>
#define PRINTF(FORMAT,args...) printf_P(PSTR(FORMAT),##args)
#else
#define PRINTF printf
#endif // CONTIKI_TARGET_AVR_RAVEN
#define PRINT6ADDR(addr) PRINTF(" %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x ", ((u8_t *)addr)[0], ((u8_t *)addr)[1], ((u8_t *)addr)[2], ((u8_t *)addr)[3], ((u8_t *)addr)[4], ((u8_t *)addr)[5], ((u8_t *)addr)[6], ((u8_t *)addr)[7], ((u8_t *)addr)[8], ((u8_t *)addr)[9], ((u8_t *)addr)[10], ((u8_t *)addr)[11], ((u8_t *)addr)[12], ((u8_t *)addr)[13], ((u8_t *)addr)[14], ((u8_t *)addr)[15])
#else
#define PRINTF(...)
#define PRINT6ADDR(addr)
#endif

#ifndef LOOCI_NF_UDP_PORT
#define LOOCI_NF_UDP_PORT 5555
#endif

#define UIP_IP_BUF   ((struct uip_udpip_hdr *)&uip_buf[UIP_LLH_LEN])

/**
 * @internal
 * Data structure for temporarily storing event before they go on the network
 */
struct looci_net_event {
  looci_eventtype_t eventtype; 
  u8_t source_cid; // source component id
  char payload[LOOCI_EVENT_PAYLOAD_MAXLEN];
};

//!@internal
//!@todo how many events do we want to queue?
//MEMB(net_events, struct looci_net_event, 2);

PROCESS(looci_networking_framework, "LooCI Networking Framework");

static struct uip_udp_conn * udpconn;

static void udp_handler(process_event_t ev, process_data_t data) {
  PRINTF("[LooCI NF] UDP Handler called\r\n");
  if(uip_udp_conn!=NULL && uip_newdata()) {
    PRINTF("[LooCI NF] uip_datalen() is %u\r\n", uip_datalen());
    struct looci_event event;
    peer_id_t peer_id = peer_get_id_or_add((peer_addr_t *) &UIP_IP_BUF->srcipaddr);
    PRINT6ADDR(&UIP_IP_BUF->srcipaddr); PRINTF("\r\n");
    PRINTF("[LooCI NF] The event is from peer %u\r\n", peer_id);
    if(peer_id == PEER_ID_NONE) {
      // Do we need to handle this in another way?
      PRINTF("[LooCI NF] Dropping incoming event due to peer library error\n");
      return;
    }
    struct looci_net_event * ne = (struct looci_net_event *) uip_appdata;
    event.type =  ne->eventtype;
    event.source_node = peer_id;
    event.source_cid = ne->source_cid;
    event.len = uip_datalen() - sizeof(struct looci_net_event) + LOOCI_EVENT_PAYLOAD_MAXLEN;
    PRINTF("[LooCI NF] Event length is %u\r\n", event.len);
    memcpy(event.payload, ne->payload, event.len);
    handle_remote_event(&event); 
    PRINTF("[LooCI NF] Done calling handle_remote_event\r\n");
  }
}

PROCESS_THREAD(looci_networking_framework, ev, data)
{
  PROCESS_BEGIN();

  PRINTF("Networking Framework starting\r\n");

  //initialization
  //memb_init(&net_events);
  peer_init();

//  udpconn = udp_new(NULL, HTONS(LOOCI_NF_UDP_PORT), NULL);
  udpconn = udp_new(NULL, 0, NULL);
  udp_bind(udpconn, HTONS(LOOCI_NF_UDP_PORT));

  while(1) {
    PROCESS_WAIT_EVENT();
    if(ev == tcpip_event && uip_udp_conn==udpconn) {
      udp_handler(ev, data);
    }
  }

  PROCESS_END();
}

void nf_send_event(struct looci_event * event, peer_id_t to) {
  // allocate space for temporarily storing the event before sending
  struct looci_net_event ne; 
  // put parameters in the net event
  ne.eventtype = event->type;
  ne.source_cid = event->source_cid;
  memcpy(ne.payload, event->payload, event->len);
  // send the event
  uip_ip6addr_t * destination = (uip_ip6addr_t *) peer_get_addr(to);
  PRINTF("[LOOCI_NF] Sending event\r\n");
  PRINTF("[LooCI_NF] Event length is %u\r\n", event->len);
  uip_udp_packet_sendto(udpconn, &ne, sizeof(struct looci_net_event) - LOOCI_EVENT_PAYLOAD_MAXLEN + event->len,
      destination, HTONS(LOOCI_NF_UDP_PORT));
}

/** @} */
